<template>
  <div class="app-container">
    <div>
      <el-table v-loading="loading" :data="assetList" @selection-change="handleSelectionChange">
<!--        <el-table-column type="selection" width="55" align="center" />-->
        <el-table-column width="200" label="资产名称" align="left" prop="name">
        </el-table-column>
        <el-table-column label="设备图片" align="center" prop="image">
          <template slot-scope="scope">
            <img v-if="scope.row.image" :src="scope.row.image" style="width: 50px;height: 50px" />
          </template>
        </el-table-column>
        <el-table-column width="200" label="资产标签" align="left" prop="asset_tag" />
        <el-table-column width="200" label="序列号" align="left" prop="serial" />
        <el-table-column width="200" label="资产型号" align="left" prop="model_name" />
        <el-table-column width="200" label="资产状态" align="center" prop="status">
          <template slot-scope="scope">
            <span v-if="scope.row.status1">{{ scope.row.status1 }}</span>
            <el-tag v-if="scope.row.assigned_to_name" type="success" style="margin-left: 12px">已分配</el-tag>
          </template>
        </el-table-column>
        <el-table-column width="200" label="位置" align="center" prop="location_name" />
        <el-table-column width="200" label="采购价格" align="center" prop="purchase_cost" />
        <el-table-column width="200" label="上次盘点时间" align="center" prop="last_audit_date" />
        <el-table-column width="200" label="下次盘点时间" align="center" prop="next_audit_date" />
        <el-table-column width="200" label="借至" align="left" prop="assigned_to_name">
          <template slot-scope="scope">
            <span>{{ scope.row.assigned_to_name?scope.row.assigned_to_name:'--' }}</span>
          </template>
        </el-table-column>
        <el-table-column width="200" label="供应商" align="left" prop="supplier_name" />
      </el-table>

      <pagination
        v-show="total>0"
        :total="total"
        :page.sync="queryParams.pageNum"
        :limit.sync="queryParams.pageSize"
        @pagination="getList"
      />
    </div>
  </div>
</template>

<script>
import { listAsset, getAsset, delAsset, addAsset, updateAsset, exportAsset, audit } from "@/api/vadmin/assets/assets";
import { listSuppliers } from "@/api/vadmin/basic/suppliers";
import { listModels } from "@/api/vadmin/basic/models";
import { listUser } from "@/api/vadmin/permission/user";
import bus from "@/utils/bus";
import _ from "lodash";
import { listLocations } from "@/api/vadmin/basic/locations/locations";
import { getAssetStatusReport } from "@/api/vadmin/report";
export default {
  name: "Asset",
  components: { },
  data() {
    return {
      formSj: {
        asset_id: null,
        check_date: null,
        notes: null,
        location: null
      },
      statusR: "",
      locationList: [],
      asset: "asset",
      titleOutOrinToo: "资产归还",
      titleOutOrin: "借出资产",
      chooseItem: null,
      step: 1,
      topId: 0,
      title1: "",
      open1: false,
      open2: false,
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // 资产表表格数据
      assetList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        name: null,
        asset_tag: null,
        serial: null,
        purchase_date: null,
        asset_eol_date: null,
        purchase_cost: null,
        order_number: null,
        assigned_to: null,
        notes: null,
        image: null,
        physical: null,
        warranty_months: null,
        depreciate: null,
        location: null,
        requestable: null,
        _snipeit_mac_address_1: null,
        accepted: null,
        last_checkout: null,
        expected_checkin: null,
        assigned_type: null,
        last_audit_date: null,
        next_audit_date: null,
        checkin_counter: null,
        checkout_counter: null,
        requests_counter: null,
        byod: null,
        model: null,
        status: null,
        supplier: null,
        deleted: true
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        name: [
          { required: true, message: "资产名称不能为空", trigger: "blur" }
        ],
        serial: [
          { required: true, message: "序列号不能为空", trigger: "blur" }
        ],
        asset_tag: [
          { required: true, message: "资产标签不能为空", trigger: "blur" }
        ],
        location: [
          { required: true, message: "地址不能为空", trigger: "change" }
        ]
      },
      suppliersList: [],
      modelsList: [],
      categoryTypeOption: [],
      outOrin: {
        asset: undefined,
        assigned_to: undefined,
        checkout_date: undefined,
        expected_checkin_date: undefined,
        checkout_notes: undefined,
        checkin_notes: undefined
      },
      roleList: [],
      assetStatus: [],
      assetStatus1: [],
      itemChoose: null,
      queryData: null,
      pieData: []
    };
  },
  created() {
    this.refresh();
  },
  mounted() {
    bus.$on("searchAssets", this.searchKey);
  },
  beforeDestroy() {
    bus.$off("searchAssets", this.searchKey);
  },
  methods: {
    refresh() {
      this.getSuppliers();
      this.getModelsList();
      listUser().then(response => {
        this.roleList = response.data.results;
      });
      listLocations().then(response => {
        this.locationList = response.data.results;
      });
      this.getDicts("asset_status").then(response => {
        this.assetStatus = response.data;
        this.assetStatus1 = response.data;
        getAssetStatusReport().then(res => {
          this.assetStatus = this.assetStatus.map(dict => {
            const status = res.data.find(status => status.status === dict.dictValue);
            return {
              dictLabel: (dict.dictLabel + "(" + status.num + ")"),
              dictValue: dict.dictValue,
              num: status ? status.num : 0
            };
          });
          this.assetStatus.unshift(
            {
              dictLabel: "全部资产",
              dictValue: "all"
            }
          );
          listAsset({ byod: true, deleted: false }).then(response => {
            this.assetStatus.push({
              dictLabel: "所有自带设备 " + "(" + response.data.count + ")",
              dictValue: "byod"
            });
            this.statusR = "all";
          });
          listAsset({ assigned_null: false, deleted: false }).then(response => {
            this.assetStatus.push({
              dictLabel: "已分配 " + "(" + response.data.count + ")",
              dictValue: "yfp"
            });
          });
        });
        this.getList();
      });
    },
    statusChange(val) {
      if (val === "yfp") {
        delete this.queryParams.byod;
        delete this.queryParams.status;
        this.queryParams.assigned_null = false;
      } else if (val === "byod") {
        delete this.queryParams.assigned_null;
        delete this.queryParams.status;
        this.queryParams.byod = true;
      } else if (val === "all") {
        delete this.queryParams.assigned_null;
        delete this.queryParams.status;
        delete this.queryParams.byod;
      } else {
        this.queryParams.status = this.statusR;
        delete this.queryParams.byod;
        delete this.queryParams.assigned_null;
      }
      this.getList();
    },
    commitLocationMethod(val) {
      this.form.location = val;
    },
    commitLocationMethod1(val) {
      this.formSj.location = val;
    },
    shengji() {
      var x = { asset_id: this.formSj.asset_id, location_id: this.formSj.location, notes: this.formSj.notes, next_audit_date: this.formSj.check_date };
      audit(x).then(res => {
        this.$message({
          message: "审计成功",
          type: "success"
        });
        this.open2 = false;
        this.getList();
      });
    },
    panPoint(val) {
      this.open2 = true;
      this.formSj.asset_id = val.id;
    },
    searchKey(e) {
      this.step = 1;
      this.queryData.searchKey = e;
      this.queryParams.asset_tag = e;
      this.getList();
    },
    submitFormOutIn() {
      this.$message({
        message: "借出成功",
        type: "success"
      });
      this.$refs.borrow.close();
      this.getList();
    },
    submitFormOutInToo() {
      this.$message({
        message: "归还成功",
        type: "success"
      });
      this.$refs.too.close();
      this.getList();
    },
    changeInOut(tag, item) {
      this.itemChoose = _.cloneDeep(item);
      this.outOrin.asset = this.itemChoose.id;
      if (tag === 1) {
        // 借出
        this.$refs.borrow.$nextTick(() => {
          this.$refs.borrow.open();
        });
      } else {
        // 归还
        this.$refs.too.$nextTick(() => {
          this.$refs.too.open();
        });
      }
    },
    clickAssets(scope) {
      this.chooseItem = scope.row;
      this.step = 2;
      this.topId = scope.row.id;
    },
    fanhui() {
      this.step = 1;
      this.getList();
    },
    getModelsList() {
      this.loading = true;
      listModels().then(response => {
        this.modelsList = response.data.results;
        this.loading = false;
      });
    },
    getSuppliers() {
      this.loading = true;
      listSuppliers().then(response => {
        this.suppliersList = response.data.results;
        this.loading = false;
      });
    },
    fileGet(file) {
      this.open1 = false;
      this.$refs.saveFile.fileList = [];
      this.form.image = file;
    },
    imageUpload() {
      this.open1 = true;
      this.title1 = "图片上传";
    },
    /** 查询资产表列表 */
    getList() {
      this.loading = true;
      if (this.queryData) {
        if (this.queryData.searchKey) {
          this.queryParams.asset_tag = _.cloneDeep(this.queryData.searchKey);
        }
      }
      listAsset(this.queryParams).then(response => {
        this.assetList = response.data.results;
        this.total = response.data.count;
        this.assetList.filter(res => {
          res.status1 = this.selectDictLabel(this.assetStatus1, res.status);
        });
        this.loading = false;
        if (this.queryData != undefined && this.queryData) {
          if (this.queryData.key === "add") {
            this.handleAdd();
          }
          if (this.queryData.searchKey) {
            if (this.assetList && this.assetList.length === 1) {
              this.chooseItem = this.assetList[0];
              this.step = 2;
              this.topId = this.chooseItem.id;
            }
            this.queryData.searchKey = null;
            if (this.$route.path !== "/assets/assets") {
              this.$router.replace("/assets/assets");
            }
          }
        }
      });
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        description: null,
        modifier: null,
        dept_belong_id: null,
        update_datetime: null,
        create_datetime: null,
        name: null,
        asset_tag: null,
        serial: null,
        purchase_date: null,
        asset_eol_date: null,
        purchase_cost: null,
        order_number: null,
        assigned_to: null,
        notes: null,
        image: null,
        physical: null,
        deleted_datetime: null,
        warranty_months: null,
        depreciate: null,
        requestable: null,
        rtd_location_id: null,
        _snipeit_mac_address_1: null,
        accepted: null,
        last_checkout: null,
        expected_checkin: null,
        assigned_type: null,
        last_audit_date: null,
        next_audit_date: null,
        // checkin_counter: null,
        // checkout_counter: null,
        // requests_counter: null,
        byod: null,
        creator_id: null,
        model_id: null,
        status: "",
        supplier_id: null
      };
      this.resetForm("form");
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id);
      this.single = selection.length !== 1;
      this.multiple = !selection.length;
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加资产表";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids;
      getAsset(id).then(response => {
        this.form = response.data;
        this.open = true;
        this.title = "修改资产表";
      });
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          if (this.form.id != null) {
            updateAsset(this.form).then(response => {
              this.$message({
                message: "修改成功",
                type: "success"
              });
              this.open = false;
              this.refresh();
            });
          } else {
            addAsset(this.form).then(response => {
              this.$message({
                message: "新增成功",
                type: "success"
              });
              this.open = false;
              this.refresh();
            });
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm("此操作将永久删除该文件, 是否继续?", "提示", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        delAsset(ids).then(res => {
          this.getList();
          this.$message({
            type: "success",
            message: "删除成功!"
          });
        });
      }).catch(() => {
        this.$message({
          type: "info",
          message: "已取消删除"
        });
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm("是否确认导出所有资产表数据项?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function() {
        return exportAsset(queryParams);
      }).then(response => {
        this.download(response.data.file_url, response.data.name);
      });
    }
  }
};
</script>
<style>
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  margin-top: 15px;
}
</style>
